package com.yy.controller;

import com.alibaba.excel.EasyExcelFactory;
import com.yy.pojo.TestUser;
import com.yy.service.Impl.TestUserServiceImpl;
import com.yy.utils.DataListener;
import com.yy.utils.R;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.net.URLEncoder;
import java.util.List;

/**
 * @author young
 * @date 2022/8/29 21:00
 * @description:
 */
@Slf4j
@RestController
@RequestMapping("/novel")
public class NovelController {
    @Autowired
    private TestUserServiceImpl testUserService;
    @GetMapping("/listNovel")
    public R<List<TestUser>> list(){
        return R.ok(testUserService.list());
    }
    
    @SneakyThrows
    @GetMapping("/down")
    public void method(HttpServletResponse response){
        List<TestUser> list = testUserService.list();
        //返回输出流_excel格式
        response.setContentType("application/octet-stream");
        String fileName = URLEncoder.encode("用户信息表","UTF-8").replace("\\","%20");
        response.setHeader("Content-disposition","attachment;filename*=utf-8''"+fileName+".xlsx");
        //输出excel信息
        EasyExcelFactory.write(response.getOutputStream(),TestUser.class).autoCloseStream(Boolean.FALSE).sheet("用户信息表").doWrite(list);
    }

    /**
     * 将Excel数据导入到数据库中
     * @param file
     * @return
     */
    @SneakyThrows
    @PostMapping("/upload")
    public R<String> upload(MultipartFile file){
        EasyExcelFactory.read(file.getInputStream(),TestUser.class,new DataListener(testUserService)).sheet().headRowNumber(1).doRead();
        return R.ok("success");
    }
}

